package org.dromara.system.controller.xcx;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.MimeTypeUtils;
import org.dromara.common.encrypt.annotation.ApiEncrypt;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.WbMinuteBidBag;
import org.dromara.system.domain.bo.*;
import org.dromara.system.domain.dto.*;
import org.dromara.system.domain.vo.*;
import org.dromara.system.service.*;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 小程序-公共接口
 *
 * @author Lion Li
 * @date 2024-05-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xcx")
public class XcxController extends BaseController {

    private final ISysDictDataService dictDataService;
    private final IWbCompanyInfoService wbCompanyInfoService;
    private final IWbItemInfoService wbItemInfoService;
    private final IWbCompanyProductListService wbCompanyProductListService;
    private final IWbCompanyBlacklistService wbCompanyBlacklistService;
    private final IWbProjectInfoService wbProjectInfoService;
    private final IWbMinuteBidBagService wbMinuteBidBagService;
    private final IWbCompanyCertService wbCompanyCertService;
    private final IWbProductAchievementService wbProductAchievementService;
    private final IWbTestEquipmentService wbTestEquipmentService;
    private final IWbProvinceService wbProvinceService;
    private final ISysUserService userService;
    private final ISysOssService ossService;
    private final IXcxFollowService xcxFollowService;
    private final IWbMinuteFileService wbMinuteFileService;
    private final IWbMinuteListService wbMinuteListService;
    private final IWbOperatingProductsListService wbOperatingProductsListService;
    private final IWbCandidateInfoService wbCandidateInfoService;
    private final IWbCandidateListService wbCandidateListService;
    private final IWbCandidateFileService wbCandidateFileService;
    private final IXcxFootprintService xcxFootprintService;
    private final IWbProductEquipmentService wbProductEquipmentService;
    /**
     * 查询字典数据列表
     */
    @GetMapping("/dict/data/list")
    public TableDataInfo<SysDictDataVo> list(SysDictDataBo dictData, PageQuery pageQuery) {
        return dictDataService.selectPageDictDataList(dictData, pageQuery);
    }

    /**
     * 根据公司ID获取公司详情信息
     *
     * @param id
     * @return
     */
    @GetMapping("/companyInfo/details/{id}")
    public R<WbCompanyInfoVo> companyInfoDetails(@NotNull(message = "主键不能为空")
                                                 @PathVariable Long id) {
        return R.ok(wbCompanyInfoService.queryDetailsById(id));
    }

    @GetMapping("/companyInfo/listMinBidBagZYT")
    public TableDataInfo<WbCompanyBidBagDTO> listMinBidBag(int flag, WbCompanyBidBagBO bo, PageQuery pageQuery) {
        return wbCompanyInfoService.queryMinBidBagList(bo, pageQuery, flag);
    }

    @GetMapping("/companyInfo/listMinBidBag")
    public TableDataInfo<WbCompanyInfoVo> listMinBidBagZYT(WbCompanyInfoBo bo, PageQuery pageQuery) {
        return wbCompanyInfoService.queryPageList_xcx(bo,pageQuery);
    }

//    @GetMapping("/companyInfo/listMinBidBagDetails")
//    public R<List> listMinBidBagDetails(Long companyInfoId,Long provinceId, String bidDate,String itemName,PageQuery pageQuery) {
//        List list = wbCompanyInfoService.listMinBidBag1(companyInfoId, provinceId, bidDate, itemName,pageQuery);
//        return R.ok(list);
//    }

    /**
     * 获取公司中标信息
     * @param bo
     * @param pageQuery
     * @return
     */
    @GetMapping("/companyInfo/listMinBidBag1")
    public TableDataInfo<Map> listMinBidBag1(WbCompanyInfoBo bo,Long provinceId,String year,String itemName, PageQuery pageQuery) {
        return wbCompanyInfoService.listMinBidBag1(bo ,provinceId,itemName, year ,pageQuery);
    }


    /**
     * 查询首页推荐公司
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @GetMapping("/companyInfo/suggest")
    public TableDataInfo<WbCompanyInfoVo> suggest(WbCompanyInfoBo bo, PageQuery pageQuery) {
        bo.setStatus("0");
        return wbCompanyInfoService.queryPageList(bo,pageQuery);
    }

    @GetMapping("/companyProductList/listSift")
    public TableDataInfo listSift(WbCompanyProductListBo bo, PageQuery pageQuery) {
        return wbCompanyProductListService.queryListSift(bo, pageQuery);
    }

    /**
     * 查询各公司产品信息列表
     */
    @GetMapping("/companyProductList/list")
    public TableDataInfo<WbCompanyProductListVo> list(WbCompanyProductListBo bo, PageQuery pageQuery) {
        return wbCompanyProductListService.queryPageList(bo, pageQuery);
    }

    @GetMapping("/companyInfo/listMinBidBagOne")
    public TableDataInfo<WbMinuteBidBag> listMinBidBagOne(WbCompanyBidBagBO bo, PageQuery pageQuery) {
        return wbCompanyInfoService.queryMinBidBagListOne(bo, pageQuery);
    }

    /**
     * 统计黑名单数量
     * @param companyName
     * @return
     */
    @GetMapping("/companyBlacklist/countProvince")
    public R<List<WbCompanyBlacklistCountProvinceDTO>> countProvince(String companyName) {
        return R.ok(wbProvinceService.provinceBlacklistNum(companyName));

    }

    /**
     *
     * 黑名单
     * @param bo
     * @param pageQuery
     * @return
     */
    @GetMapping("/companyBlacklist/provinceId")
    public TableDataInfo<WbCompanyBlacklistVo> provinceBlacklist(WbCompanyBlacklistBo bo, PageQuery pageQuery) {
        return  wbCompanyBlacklistService.queryPageListXcx(bo, pageQuery);
    }

    /**
     * 查询企业黑名单列表
     */
    @GetMapping("/companyBlacklist/list")
    public TableDataInfo<WbCompanyBlacklistVo> list(WbCompanyBlacklistBo bo, PageQuery pageQuery) {
        return wbCompanyBlacklistService.queryPageList(bo, pageQuery);
    }

    /**
     * 按照物质来统计黑名单数量
     * @param disposeWay
     * @return
     */
    @GetMapping("/companyBlacklist/countProduct")
    public R<List<WbCompanyBlacklistCountProductDTO>> countProduct(String disposeWay) {
        return R.ok(wbCompanyBlacklistService.queryCountProduct(disposeWay));

    }

    @GetMapping("/projectInfo/list")
    public TableDataInfo<WbProjectInfoVo> list(WbProjectInfoBo bo, PageQuery pageQuery) {
        return wbProjectInfoService.queryPageListZ(bo, pageQuery);
    }

    @GetMapping("/minuteBidBag/listSiftZYT")
    public R<WbMinuteBidBagSiftDTO> listSift(WbMinuteBidBagBo bo, PageQuery pageQuery) {
        return wbMinuteBidBagService.queryListSift(bo, pageQuery);
    }
    /**
     * 查询省份列表
     */
    @GetMapping("/minuteBidBag/listSift")
    public TableDataInfo<WbProvinceVo> listZYT(WbProvinceDTO dto,PageQuery pageQuery) {
        return  wbProvinceService.queryListZYQ(dto,pageQuery);
    }

    /**
     * 查询省份_
     */
    @GetMapping("/province/list")
    public R< List<WbProvinceVo>> provinceList() {
        WbProvinceBo bo = new WbProvinceBo();
        List<WbProvinceVo> wbProvinceVos = wbProvinceService.queryList(bo);
        return  R.ok(wbProvinceVos);
    }


    /**
     * 获取中标结果公告详细信息
     *
     * @param id 主键
     */
    @GetMapping("/minuteBidBag/{id}")
    public R<Map<String,Object> > getMinuteBidBagInfo(@NotNull(message = "主键不能为空") @PathVariable Long id, PageQuery pageQuery) {

        //中标详情
        Map<String,Object> map = new HashMap<>();
        WbMinuteBidBagVo wbMinuteBidBagVo = wbMinuteBidBagService.queryById(id);
        map.put("MinuteBidBag",wbMinuteBidBagVo);

        //附件
        WbMinuteFileBo wbMinuteFileBo = new WbMinuteFileBo();
        wbMinuteFileBo.setWbMinuteBidBagId(id);
        List<WbMinuteFileVo> wbMinuteFileVos = wbMinuteFileService.queryList(wbMinuteFileBo);
        map.put("MinuteFile",wbMinuteFileVos);

        //分包
        WbMinuteListBo wbMinuteListBo = new WbMinuteListBo();
        wbMinuteListBo.setWbMinuteBidBagId(id);
        TableDataInfo<WbMinuteListVo> wbMinuteListVos = wbMinuteListService.queryPageList(wbMinuteListBo,pageQuery);
        map.put("MinuteList",wbMinuteListVos);

        //关联公告
        if(StringUtils.isNotEmpty(wbMinuteBidBagVo.getItemId())){
            WbItemInfoBo wbItemInfoBo = new WbItemInfoBo();
            wbItemInfoBo.setItemId(wbMinuteBidBagVo.getItemId());
            List<WbItemInfoVo> wbItemInfoVos = wbItemInfoService.queryList(wbItemInfoBo);
            map.put("wbItemInfo",wbItemInfoVos);
        }

        //保存我的足迹
        if (LoginHelper.getLoginUser() != null ){
            XcxFootprintBo xcxFootprintBo = new XcxFootprintBo();
            xcxFootprintBo.setFootprintId(id);
            xcxFootprintBo.setFootprintType("03");
            xcxFootprintBo.setCreateBy(LoginHelper.getUserId());
            //查询用户今天是否查看了这条数据，如果看了就更新，如果没看就添加
            XcxFootprintVo xcxFootprintVo = xcxFootprintService.queryListZYT(xcxFootprintBo);
            if (xcxFootprintVo == null){
                xcxFootprintService.insertByBo(xcxFootprintBo);
            }else {
                xcxFootprintBo.setId(xcxFootprintVo.getId());
                xcxFootprintService.updateByBo(xcxFootprintBo);
            }
        }
        return R.ok(map);
    }

    /**
     * 获取推荐候选人公告详细信息
     * @param id
     * @return
     */
    @GetMapping("/wbCandidateInfo/{id}")
    public R<Map<String,Object> > getWbCandidateInfo(@NotNull(message = "主键不能为空") @PathVariable Long id, PageQuery pageQuery) {

        //候选人详情
        Map<String,Object> map = new HashMap<>();
        WbCandidateInfoVo wbCandidateInfoVo = wbCandidateInfoService.queryById(id);
        map.put("wbCandidateInfoVo",wbCandidateInfoVo);

        //附件
        WbCandidateFileBo wbCandidateFileBo = new WbCandidateFileBo();
        wbCandidateFileBo.setCandidateId(id);
        List<WbCandidateFileVo> list_wbCandidateFileVo = wbCandidateFileService.queryList(wbCandidateFileBo);
        map.put("files",list_wbCandidateFileVo);

        //分包
        WbCandidateListBo wbCandidateListBo = new WbCandidateListBo();
        wbCandidateListBo.setCandidateId(id);
        TableDataInfo<WbCandidateListVo> list_WbCandidateListVo = wbCandidateListService.queryPageList(wbCandidateListBo,pageQuery);
        map.put("wbCandidateList",list_WbCandidateListVo);

        //关联公告
        if(wbCandidateInfoVo != null && StringUtils.isNotEmpty(wbCandidateInfoVo.getPurchaseNo())){
            WbItemInfoBo wbItemInfoBo = new WbItemInfoBo();
            wbItemInfoBo.setItemId(wbCandidateInfoVo.getPurchaseNo());
            List<WbItemInfoVo> wbItemInfoVos = wbItemInfoService.queryList(wbItemInfoBo);
            map.put("wbItemInfo",wbItemInfoVos);
        }
        //保存我的足迹
        if (LoginHelper.getLoginUser() != null ){
            XcxFootprintBo xcxFootprintBo = new XcxFootprintBo();
            xcxFootprintBo.setFootprintId(id);
            xcxFootprintBo.setFootprintType("04");
            xcxFootprintBo.setCreateBy(LoginHelper.getUserId());
            //查询用户今天是否查看了这条数据，如果看了就更新，如果没看就添加
            XcxFootprintVo xcxFootprintVo = xcxFootprintService.queryListZYT(xcxFootprintBo);
            if (xcxFootprintVo == null){
                xcxFootprintService.insertByBo(xcxFootprintBo);
            }else {
                xcxFootprintBo.setId(xcxFootprintVo.getId());
                xcxFootprintService.updateByBo(xcxFootprintBo);
            }
        }
        return R.ok(map);
    }
    /**
     * 查询企业黑名单
     */

    @GetMapping("/companyInfo/listBlack")
    public TableDataInfo<WbCompanyBlacklistVo> listBlack(String blacklistStatus, String companyName, PageQuery pageQuery) {
        TableDataInfo<WbCompanyBlacklistVo> wbCompanyBlacklistVoTableDataInfo = wbCompanyBlacklistService.queryBlackOne( blacklistStatus,companyName , pageQuery);
        return wbCompanyBlacklistVoTableDataInfo;
    }

    /**
     * 查询企业资质证书列表
     */
    @GetMapping("/companyCert/list")
    public TableDataInfo<WbCompanyCertVo> list(WbCompanyCertBo bo, PageQuery pageQuery) {
        bo.setDataTagging("1");
        return wbCompanyCertService.queryPageList(bo, pageQuery);
    }

    @GetMapping("/productAchievement/listSift")
    public R<List<WbOperatingProductsListVo>> listSift(WbOperatingProductsListBo bo) {
        return R.ok(wbOperatingProductsListService.queryList(bo));
    }

    @GetMapping("/companyInfo/listPlantEquipment")
    public TableDataInfo<WbProductEquipmentVo> listPlantEquipment(WbProductEquipmentBo bo, PageQuery pageQuery) {
        bo.setDataTagging("1");
        return wbProductEquipmentService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询试验检测设备列表
     */
    @GetMapping("/testEquipment/list")
    public TableDataInfo<WbTestEquipmentVo> list(WbTestEquipmentBo bo, PageQuery pageQuery) {
        bo.setDataTagging("1");
        return wbTestEquipmentService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询产品业绩列表
     */
    @GetMapping("/productAchievement/list")
    public TableDataInfo<WbProductAchievementVo> list(WbProductAchievementBo bo, PageQuery pageQuery) {
        bo.setDataTagging("1");
        return wbProductAchievementService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询全部中标项目
     */
    @GetMapping("/wbMinuteBidBag/list")
    public TableDataInfo<WbMinuteBidBagVo> wbMinuteBidBagList(WbMinuteBidBagBo bo, PageQuery pageQuery) {
        return wbMinuteBidBagService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询公司列表
     */
    @GetMapping("/companyInfo/list")
    public TableDataInfo<WbCompanyInfoVo> list(WbCompanyInfoBo bo, PageQuery pageQuery) {
        bo.setStatus("0");
        pageQuery.setOrderByColumn("suggestOrder,suggestStatus,createTime,id");
        pageQuery.setIsAsc("ascending,descending,ascending,descending");
        return wbCompanyInfoService.queryPageList(bo,pageQuery);
    }

    /**
     * 获取公司详细信息
     *
     * @param id 主键
     */
    @GetMapping("/companyInfo/{id}")
    public R<WbCompanyInfoVo> getInfo(@NotNull(message = "主键不能为空")
                                      @PathVariable Long id) {
        return R.ok(wbCompanyInfoService.queryById(id));
    }
    /**
     * 个人信息
     */
    @GetMapping("/user/profile")
    public R<ProfileVo> profile() {
        SysUserVo user = userService.selectUserById(LoginHelper.getUserId());
        ProfileVo profileVo = new ProfileVo();
        profileVo.setUser(user);
        profileVo.setRoleGroup(userService.selectUserRoleGroup(user.getUserName()));
        profileVo.setPostGroup(userService.selectUserPostGroup(user.getUserName()));
        return R.ok(profileVo);
    }
    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/user/profile")
    public R<Void> updateProfile(@RequestBody SysUserProfileBo profile) {
        SysUserBo user = BeanUtil.toBean(profile, SysUserBo.class);
        String username = LoginHelper.getUsername();
        Long userId = LoginHelper.getUserId();
        user.setUserId(userId);
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("修改用户'" + username + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.fail("修改用户'" + username + "'失败，邮箱账号已存在");
        }
        user.setUserId(LoginHelper.getLoginUser().getUserId());
        if (userService.updateUserProfile(user) > 0) {
            return R.ok();
        }
        return R.fail("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     *
     * @param bo 新旧密码
     */
    @ApiEncrypt
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/user/profile/updatePwd")
    public R<Void> updatePwd(@Validated @RequestBody SysUserPasswordBo bo) {
        SysUserVo user = userService.selectUserById(LoginHelper.getUserId());
        String password = user.getPassword();
        if (!BCrypt.checkpw(bo.getOldPassword(), password)) {
            return R.fail("修改密码失败，旧密码错误");
        }
        if (BCrypt.checkpw(bo.getNewPassword(), password)) {
            return R.fail("新密码不能与旧密码相同");
        }

        if (userService.resetUserPwd(user.getUserId(), BCrypt.hashpw(bo.getNewPassword())) > 0) {
            return R.ok();
        }
        return R.fail("修改密码异常，请联系管理员");
    }

    /**
     * 删除我的关注
     *
     */
    @Log(title = "我的关注", businessType = BusinessType.DELETE)
    @PostMapping("/follow/deleteFollow")
    public R<Void> deleteFollow(@RequestBody  XcxFollowBo bo) {
        bo.setCreateBy(LoginHelper.getUserId());
        List<XcxFollowVo> followVoList = xcxFollowService.queryList(bo);
        if (followVoList.size() > 0){
            List<Long> idList = new ArrayList<>();
            for (XcxFollowVo xcxFollowVo:followVoList) {
                idList.add(xcxFollowVo.getId());
            }
            return toAjax(xcxFollowService.deleteWithValidByIds(idList, true));
        }

        return R.fail("未查询到相应的关注信息");
    }

    /**
     * 头像上传
     *
     * @param avatarfile 用户头像
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/user/profile/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<AvatarVo> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) {
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            SysOssVo oss = ossService.upload(avatarfile);
            String avatar = oss.getUrl();
            if (userService.updateUserAvatar(LoginHelper.getUserId(), oss.getOssId())) {
                AvatarVo avatarVo = new AvatarVo();
                avatarVo.setImgUrl(avatar);
                return R.ok(avatarVo);
            }
        }
        return R.fail("上传图片异常，请联系管理员");
    }
    }
